#include "sapmsginterfacei.h"

//sapMsgInterface* sapMsgInterface::instance=nullptr;
//QMutex sapMsgInterface::mutex;

//STATEMENTINSTANCE(sapMsgInterface)
#define ASMORDERDBSTR ConnectPoolFactory::getInstance()->getConnectPool(ConnectPoolFactory::AsmOrderDataBase0)

sapMsgInterfaceI::sapMsgInterfaceI(QObject *parent) : QObject(parent)
{
    qRegisterMetaType<QList<labelMsgStruct >>("QList<labelMsgStruct >");
    qRegisterMetaType<QList<retMsgStructI >>("QList<retMsgStruct >");

    connect(&NetworkMgr, SIGNAL(finished(QNetworkReply *)),SLOT(ReadResponse(QNetworkReply *)));

    connect(this,&sapMsgInterfaceI::ReplyError,this,&sapMsgInterfaceI::ONReplyError);

    MsgTimer = new QTimer(this);
    connect(MsgTimer,&QTimer::timeout,this,&sapMsgInterfaceI::sapMsgTimer);
    MsgTimer->start(300);

}

void sapMsgInterfaceI::sapMsgTimer()
{
    if(WebServiceItiemMap.isEmpty() && !WebServiceMap.isEmpty()){
        WebServiceI WebServiceI= WebServiceMap.first();
        setWebService_Get(WebServiceI.LabelNo,sapPathMap.value(WebServiceI.pathId).Path+WebServiceI.LabelNo,
                          WebServiceI.UserBadge,sapPathMap.value(WebServiceI.pathId).Type);
        WebServiceMap.remove(WebServiceI.LabelNo);
        qDebug()<<"WS01 LabelNo 0:"<<WebServiceI.LabelNo<<"  size: "<<WebServiceMap.size()<<WebServiceItiemMap.size();
    }

}

//平板向主控http请求失败，服务器在线状态判断
bool sapMsgInterfaceI::TabletDisConnet()
{
    return isOlien;
}

//SAP 返回数据
void sapMsgInterfaceI::ReadResponse(QNetworkReply *Reply)
{
    switch (Reply->error()) {
        case QNetworkReply::NoError:
        case QNetworkReply::ContentAccessDenied://数据库拒绝访问
        case QNetworkReply::ContentOperationNotPermittedError://内容操作批准未通过
        case QNetworkReply::ContentNotFoundError://内容没有找到
        case QNetworkReply::UnknownContentError:
        {
            QByteArray ReplyData;
            ReplyData=Reply->readAll();
            //qDebug()<<"ReplyData: "<<ReplyData;
            QJsonDocument JsonAnalyse; QJsonParseError JsonError;
            QJsonArray Jsonarray;
            JsonAnalyse = QJsonDocument::fromJson(ReplyData,&JsonError);

//            qDebug() << "Reply->readAll(): " << JsonAnalyse;

            if(JsonError.error == QJsonParseError::NoError)
            {
                if(!(JsonAnalyse.isEmpty() || JsonAnalyse.isNull()))
                {
                    for(int i=0;i<WebServiceItiemMap.length();i++){
                        if(WebServiceItiemMap[i].NetworkRepItiem==Reply){
//                            qDebug()<<"actionType:"<<WebServiceItiemMap[i].actionType<<WebServiceItiemMap[i].ikey<<"\n"
//                                                                  <<"JsonAnalyse:"<<JsonAnalyse;
                            analysReplyJson(WebServiceItiemMap[i].ikey,JsonAnalyse,WebServiceItiemMap[i].actionType);
                            WebServiceItiemMap[i].NetworkRepItiem->deleteLater();//关闭
//                            WebServiceItiemMap[i].timeout->disconnect();//disconnect 槽函数
//                            WebServiceItiemMap[i].timeout->stop();//关闭
//                            WebServiceItiemMap[i].timeout->deleteLater();//关闭
                            WebServiceItiemMap[i].process = true;
                            WebServiceItiemMap.removeAt(i);
                            i--;

                            CurrentSendII.ReplyData=ReplyData;
                            CurrentSendII.Errorinfo="";
                            isOlien = true;

                        }
                    }
                }
            }
        }
            break;
        default:
        {
            // HTTP错误代码解析: https://blog.csdn.net/qq_32963841/article/details/78365449
            int HttpStatus = Reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();//错误代码
            QString Errorinfo="error http Status: "+QString::number(HttpStatus);
            QString Errorinfo1=(QString("Network transport error (%1): %2").arg(Reply->error()).arg(Reply->errorString()));//系统信息

            QJsonObject ReplyJson ;
            QJsonDocument JsonAnalyse; QJsonParseError JsonError;
            for(int i=0;i<WebServiceItiemMap.length();i++){
                if(WebServiceItiemMap[i].NetworkRepItiem==Reply){
                    QByteArray ReplyData;
                    ReplyData=Reply->readAll();
                    JsonAnalyse = QJsonDocument::fromJson(ReplyData,&JsonError);
                    //qDebug()<<QDateTime::currentDateTime().toString("yyyy-MM-dd_hh:mm:ss")<<"ikey:"<<WebServiceItiemMap[i].ikey<<"size:"<<WebServiceItiemMap.size();
//                    qDebug()<<Errorinfo<<Errorinfo1<<Reply->error();
                    //qDebug()<<"ReplyData: "<<ReplyData;

                    CurrentSendII.ReplyData=ReplyData;
                    CurrentSendII.Errorinfo=QDateTime::currentDateTime().toString("yyyy-MM-dd_hh:mm:ss")+"   "+
                            Errorinfo+Errorinfo1;

                    ReplyJson.insert("result","E1");
                    ReplyJson.insert("message","请求超时");
                    analysReplyJson(WebServiceItiemMap[i].ikey,JsonAnalyse,WebServiceItiemMap[i].actionType);
//                    WebServiceItiemMap[i].NetworkRepItiem->deleteLater();//关闭
//                    WebServiceItiemMap.removeAt(i);i--;

                    emit ReplyError(WebServiceItiemMap[i]);//因网络异常 重发 三次机制
                }
            }

        }
        break;
    }
}

void sapMsgInterfaceI::ONReplyError(WebServiceItiemI WebServiceItiemI)
{
    int count=1;
    if(currentIkeyMap.contains(WebServiceItiemI.ikey)){
        qDebug()<<"重发结束 ONReplyError e: "<<WebServiceItiemI.ikey<<WebServiceItiemI.actionType<<"第几次: "<<count;
        return;
    }

    if(!currentIkeyMap.contains(WebServiceItiemI.ikey)){
        currentIkeyMap.insert(WebServiceItiemI.ikey,count);
    }
    qDebug()<<"ONReplyError: "<<WebServiceItiemI.ikey<<WebServiceItiemI.actionType<<"第几次: "<<count;
    isOlien = false;
}


//SAP 反馈数据解析
void sapMsgInterfaceI::analysReplyJson(QString iKey, QJsonDocument JsonAnalyse, QString actionType)
{
    QJsonObject ReplyJson = JsonAnalyse.object();
    if(actionType=="action1" || actionType=="action3"){
         setMsgRecv_Msg(iKey,ReplyJson,actionType); //获取信息返回
    }if(actionType=="action6" || actionType=="action0"){
        setMsgRecv_Mes(iKey,ReplyJson); //获取信息返回
    }
    //qDebug()<<"analysReplyJson   iKey:"<<iKey<<" actionType:"<<actionType<<"  :"<<JsonAnalyse.isEmpty();
}

void sapMsgInterfaceI::setSapPathMap(QMap<int ,sapPath >sapPathMap0)
{
    sapPathMap=sapPathMap0;
}

void sapMsgInterfaceI::setCurrentSend(CurrentSendI CurrentSend0)
{
    CurrentSendII=CurrentSend0;
}

CurrentSendI sapMsgInterfaceI::getCurrentSend()
{
    return CurrentSendII;
}

void sapMsgInterfaceI::setCurrentSend_(CurrentSendI CurrentSend0)
{
    qDebug()<<" setCurrentSend_:"<<CurrentSend0.UrlPath<<CurrentSend0.ReplyData<<CurrentSend0.postJson;
    CurrentSendI_=CurrentSend0;
}

CurrentSendI sapMsgInterfaceI::getCurrentSend_()
{
    return CurrentSendI_;
}

void sapMsgInterfaceI::setIsLien(bool newisOlien)
{
    isOlien = newisOlien;
}


//<<<<<<<<<<WS01<<<<<<<<<<<<
void sapMsgInterfaceI::getLabelMsg(QString LabelNo, QString UserBadge,int pathId)
{
    WebServiceI WebServiceI;
    WebServiceI.LabelNo=LabelNo;
    WebServiceI.UserBadge=UserBadge;
    WebServiceI.pathId=pathId;
    if(WebServiceItiemMap.size()<WebConut){
        setWebService_Get(LabelNo,sapPathMap.value(pathId).Path+LabelNo,UserBadge,sapPathMap.value(pathId).Type);
        return;
    }
    if(!WebServiceMap.contains(LabelNo)){
        WebServiceMap.insert(WebServiceI.LabelNo,WebServiceI);
    }

}

//<<<<<<<<<< Reply<<<<<<<<<<<<
void sapMsgInterfaceI::setMsgRecv_Msg(QString iKey, QJsonObject ReplyJson,QString actionType)
{
    ReplyMsg ReplyMsgI;
    ReplyMsgI.keyId=iKey;
    if(!ReplyJson.isEmpty()){
        ReplyMsgI.status=ReplyJson.value("retcode").toInt();
        ReplyMsgI.errorMsg=ReplyJson.value("message").toString();
    }else{
        ReplyMsgI.status=-1;
        ReplyMsgI.errorMsg="提交失败";
    }
    ReplyMsgI.ReplyJson=ReplyJson;
    ReplyMsgMap.insert(iKey,ReplyMsgI);
    qDebug()<<actionType<<"<<<<< set setMsgRecv_Msg <<<<< iKey:"<<iKey<<" status:"<<ReplyMsgI.status<<" errorMsg:"<<ReplyMsgI.errorMsg<<" Json:"<<ReplyMsgI.ReplyJson;
}

ReplyMsg sapMsgInterfaceI::GetMsgRecv_Msg(QString iKey)
{
    ReplyMsg ReplyMsgI;
    if(ReplyMsgMap.contains(iKey)){
        ReplyMsgI=ReplyMsgMap.value(iKey);
        ReplyMsgMap.remove(iKey);
        qDebug()<<"<<<<< get GetMsgRecv_Msg <<<<< keyId:"<<iKey<<" status:" <<ReplyMsgI.status<<" errorMsg:"<<ReplyMsgI.errorMsg<<ReplyMsgI.datalist.size();
    }
    return ReplyMsgI;
}

void sapMsgInterfaceI::setMsgRecv_Mes(QString iKey,QJsonObject ReplyJson)
{
    ReplyMsg ReplyMsgI;
    ReplyMsgI.keyId=iKey;
    ReplyMsgI.ReplyJson=ReplyJson;         //数据包
    ReplyMsgMap.insert(iKey,ReplyMsgI);
//    qDebug()<<"set setMsgRecv_Mes--->iKey:"<<iKey<<" Json:"<<ReplyMsgI.ReplyJson;
}

ReplyMsg sapMsgInterfaceI::GetMsgRecv_Mes(QString iKey)
{
    ReplyMsg ReplyMsgI;
    if(ReplyMsgMap.contains(iKey)){
        ReplyMsgI=ReplyMsgMap.value(iKey);
        ReplyMsgMap.remove(iKey);
//        qDebug()<<"get GetMsgRecv_Mes --> keyId:"<<iKey;
    }
    return ReplyMsgI;
}

/************************** 任务函数  ***************************/

void sapMsgInterfaceI::newSAPExcelInfo_POst(QString iKey, QJsonObject SAPJson, QString UserBadge, int pathId)
{
    qDebug()<<"newSAPExcelInfo--->POst"<<iKey<<UserBadge<<pathId<<sapPathMap.value(pathId).Path<<sapPathMap.value(pathId).Type;
    setWebService_Post(iKey,sapPathMap.value(pathId).Path,SAPJson,UserBadge,sapPathMap.value(pathId).Type);
}

void sapMsgInterfaceI::querySAPExcelInfo_POst(QString iKey, QJsonObject SAPJson, QString UserBadge, int pathId)
{
    setWebService_Post(iKey,sapPathMap.value(pathId).Path,SAPJson,UserBadge,sapPathMap.value(pathId).Type);
    qDebug()<<"querySAPExcelInfo_POst"<<iKey<<UserBadge<<pathId<<sapPathMap.value(pathId).Path<<sapPathMap.value(pathId).Type;
}

void sapMsgInterfaceI::queryStation_POst(QString iKey, QJsonObject SAPJson, QString UserBadge, int pathId)
{
    qDebug()<<"queryStation_POst"<<iKey<<UserBadge<<pathId<<sapPathMap.value(pathId).Path<<sapPathMap.value(pathId).Type;
    setWebService_Post(iKey,sapPathMap.value(pathId).Path,SAPJson,UserBadge,sapPathMap.value(pathId).Type);
}


/************************** Get 与 POST 接口封装函数  ***************************/

//Get SAP 数据
void sapMsgInterfaceI::setWebService_Get(QString LabelNo, QString UrlPath, QString UserBadge, QString Type)
{
    allWebConut++;
    QUrl url(UrlPath);
    QNetworkRequest NetworkRequest;
    NetworkRequest.setUrl(url);
    NetworkRequest.setRawHeader("User",QString("{%1}").arg("User6537").toLatin1());
    NetworkRequest.setRawHeader("Accept-Language","{en-US}");
    QNetworkReply*  NetworkReply = NetworkMgr.get(NetworkRequest);

    for(int i=0;i<WebServiceItiemMap.length();i++){
        if(WebServiceItiemMap[i].ikey==LabelNo){
            WebServiceItiemMap[i].NetworkRepItiem->deleteLater();//关闭
            WebServiceItiemMap[i].timeout->disconnect();//disconnect 槽函数
            WebServiceItiemMap[i].timeout->stop();//关闭
            WebServiceItiemMap[i].timeout->deleteLater();//关闭
            WebServiceItiemMap[i].process = true;
            WebServiceItiemMap.removeAt(i);i--;
            qDebug()<<"WebServiceItiemMap.removeAt(i) "<<UrlPath;
        }
    }

    WebServiceItiemI WebServiceItiem0;
    WebServiceItiem0.ikey=LabelNo;             //唯一键
    WebServiceItiem0.UrlPath=UrlPath;       //路径
    WebServiceItiem0.actionType=Type;       //操作类型  WS02 WS03 …… post
    WebServiceItiem0.userBadge=UserBadge;   //员工工号
    WebServiceItiem0.LabelNo=LabelNo;
    WebServiceItiem0.NetworkRepItiem=NetworkReply;
    WebServiceItiemMap.append(WebServiceItiem0);
    CurrentSendII.UrlPath=UrlPath;

//    qDebug()<<WebServiceItiem0.actionType<<"  ikey:"<<WebServiceItiem0.ikey<<"  Send UrlPath: "<<UrlPath;

}

//post 数据给 SAP
void sapMsgInterfaceI::setWebService_Post(QString iKey,QString UrlPath, QJsonObject postJson,
                                         QString UserBadge, QString Type)
{
    QUrl url(UrlPath);
    QNetworkRequest NetworkRequest;
    NetworkRequest.setUrl(url);//地址信息

    NetworkRequest.setRawHeader("User",QString("{%1}").arg(UserBadge).toLatin1());
    NetworkRequest.setRawHeader("Accept-Language","{en-US}");//选中语言类型
    NetworkRequest.setHeader(QNetworkRequest::ContentTypeHeader,"application/json;charset=utf-8");//"text/json" 内容编码类型
    QNetworkReply*NetworkReply=NetworkMgr.post(NetworkRequest,QJsonDocument(postJson).toJson());

    for(int i=0;i<WebServiceItiemMap.length();i++){
        if(WebServiceItiemMap[i].ikey==iKey){
            WebServiceItiemMap[i].NetworkRepItiem->deleteLater();//关闭
            WebServiceItiemMap[i].timeout->disconnect();//disconnect 槽函数
            WebServiceItiemMap[i].timeout->stop();//关闭
            WebServiceItiemMap[i].timeout->deleteLater();//关闭
            WebServiceItiemMap[i].process = true;
            WebServiceItiemMap.removeAt(i);i--;
        }
    }

    WebServiceItiemI WebServiceItiem0;
    WebServiceItiem0.ikey=iKey;             //唯一键
    WebServiceItiem0.UrlPath=UrlPath;       //路径
    WebServiceItiem0.queryJson=postJson;    //请求数据
    WebServiceItiem0.userBadge=UserBadge;   //员工工号
    WebServiceItiem0.actionType=Type;       //操作类型  WS02 WS03 …… post

    WebServiceItiem0.NetworkRepItiem=NetworkReply;
    QTimer *tmp = new QTimer;
    WebServiceItiem0.timeout=tmp;
    WebServiceItiemMap.append(WebServiceItiem0);

    {
        //超时抛弃
        connect(WebServiceItiem0.timeout, &QTimer::timeout, this, [=]
        {
//            qDebug() << "timer out addr " << tmp;
            if(!WebServiceItiem0.process && !NetworkReply->isFinished())
            {
                qDebug() << "cannot get feedback " << url;
                NetworkReply->abort();
            }
        });
        WebServiceItiem0.timeout->start(5000);
    }

    qDebug() << "AGV状态查询: "<< Type << " UrlPath: "<< UrlPath << " postJson: "<< postJson;

    CurrentSendII.UrlPath=UrlPath;
    CurrentSendII.postJson=postJson;

}


void sapMsgInterfaceI::setWebService_Post_WS06(QString iKey, QString UrlPath, QJsonArray postJson, QString UserBadge, QString Type)
{
    QUrl url(UrlPath);
    QNetworkRequest NetworkRequest;
    NetworkRequest.setUrl(url);//地址信息

    NetworkRequest.setRawHeader("User",QString("{%1}").arg(UserBadge).toLatin1());
    NetworkRequest.setRawHeader("Accept-Language","{en-US}");//选中语言类型
    NetworkRequest.setHeader(QNetworkRequest::ContentTypeHeader,"application/json;charset=utf-8");//"text/json" 内容编码类型
    QNetworkReply*NetworkReply=NetworkMgr.post(NetworkRequest,QJsonDocument(postJson).toJson());

    for(int i=0;i<WebServiceItiemMap.length();i++){
        if(WebServiceItiemMap[i].ikey==iKey){
            WebServiceItiemMap[i].NetworkRepItiem->deleteLater();//关闭
            WebServiceItiemMap[i].timeout->disconnect();//disconnect 槽函数
            WebServiceItiemMap[i].timeout->stop();//关闭
            WebServiceItiemMap[i].timeout->deleteLater();//关闭
            WebServiceItiemMap[i].process = true;
            WebServiceItiemMap.removeAt(i);i--;
        }
    }

    WebServiceItiemI WebServiceItiem0;
    WebServiceItiem0.ikey=iKey;             //唯一键
    WebServiceItiem0.UrlPath=UrlPath;       //路径
    WebServiceItiem0.actionType=Type;       //操作类型  WS02 WS03 …… post
    WebServiceItiem0.userBadge=UserBadge;   //员工工号
    WebServiceItiem0.postArray=postJson;    //请求数据
    WebServiceItiem0.NetworkRepItiem=NetworkReply;
    WebServiceItiem0.timeout=new QTimer;
    WebServiceItiemMap.append(WebServiceItiem0);

    {
        //超时抛弃
        connect(WebServiceItiem0.timeout, &QTimer::timeout, this, [=]
        {
//            qDebug() << "timer out addr " << tmp;
            if(!WebServiceItiem0.process && !NetworkReply->isFinished())
            {
                qDebug() << "cannot get feedback " << url;
                NetworkReply->abort();
            }
        });
        WebServiceItiem0.timeout->start(5000);
    }

    CurrentSendII.UrlPath=UrlPath;
    //CurrentSendI.postJson=postJson;

    qDebug()<<"UrlPath: "<<UrlPath;
    qDebug()<<"postJson: "<<postJson;

}

void sapMsgInterfaceI::setWebService_SAOP_Post(QString iKey, QString UrlPath, QDomDocument doc, QString UserBadge, QString Type)
{
    QUrl url(UrlPath);
    QNetworkRequest NetworkRequest;
    NetworkRequest.setUrl(url);//地址信息

    NetworkRequest.setHeader(QNetworkRequest::ContentTypeHeader,"text/xml;charset=utf-8");//"text/json" 内容编码类型
    NetworkRequest.setRawHeader("SOAPAction", "http://tempuri.org/IJDSWS/PrintLabel");
    QNetworkReply*NetworkReply=NetworkMgr.post(NetworkRequest,doc.toString().toUtf8().constData());


    for(int i=0;i<WebServiceItiemMap.length();i++){
        if(WebServiceItiemMap[i].ikey==iKey){
            WebServiceItiemMap[i].NetworkRepItiem->deleteLater();//关闭
            WebServiceItiemMap[i].timeout->disconnect();//disconnect 槽函数
            WebServiceItiemMap[i].timeout->stop();//关闭
            WebServiceItiemMap[i].timeout->deleteLater();//关闭
            WebServiceItiemMap[i].process = true;
            WebServiceItiemMap.removeAt(i);i--;
        }
    }

    WebServiceItiemI WebServiceItiem0;
    WebServiceItiem0.ikey=iKey;             //唯一键
    WebServiceItiem0.UrlPath=UrlPath;       //路径
    WebServiceItiem0.actionType=Type;       //操作类型  WS02 WS03 …… post
    WebServiceItiem0.userBadge=UserBadge;   //员工工号
    WebServiceItiem0.doc=doc;               //请求数据
    WebServiceItiem0.NetworkRepItiem=NetworkReply;
    WebServiceItiem0.timeout=new QTimer;
    WebServiceItiemMap.append(WebServiceItiem0);

    {
        //超时抛弃
        connect(WebServiceItiem0.timeout, &QTimer::timeout, this, [=]
        {
//            qDebug() << "timer out addr " << tmp;
            if(!WebServiceItiem0.process && !NetworkReply->isFinished())
            {
                qDebug() << "cannot get feedback " << url;
                NetworkReply->abort();
            }
        });
        WebServiceItiem0.timeout->start(5000);
    }

    CurrentSendII.UrlPath=UrlPath;
    CurrentSendII.postdoc=doc;

    qDebug()<<"UrlPath: "<<UrlPath;
    qDebug()<<"DOC: "<<doc.toString().toUtf8().constData();

}
